import React, { PureComponent } from 'react';
import { Card, Form, Row, Select, DatePicker, Button, Col, Spin } from 'antd';
import { Chart, Axis, Tooltip, Geom, Label } from 'bizcharts';
import { connect } from 'dva';
import lodash from 'lodash';
import moment from 'moment';
import numeral from 'numeral';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { SqlHistogramArray } from '../../utils/enum';
// import classNames from 'classnames';
import styles from './SqlsDiff.less'

@connect(({ GlobalEnumModel, SqlsDiffModel, loading }) => ({
  GlobalEnumModel,
  SqlsDiffModel,
  quetyLoading: loading.effects['SqlsDiffModel/findDiffData'],
}))
@Form.create()
export default class SqlsDiff extends PureComponent {

  // 数据初始化
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'GlobalEnumModel/allSysName' });
    this.findDiffData();
  }

  // 查询数据
  findDiffData = (e) => {
    if (e) e.preventDefault();
    const { dispatch, form } = this.props;
    const queryParam = form.getFieldsValue();
    dispatch({ type: 'SqlsDiffModel/findDiffData', payload: { ...queryParam, pageNo: 0 } });
  }

  // 查询表单
  queryForm() {
    const {
      form: { getFieldDecorator },
      queryLoading,
      GlobalEnumModel: { sysNameList, currentSysName },
      SqlsDiffModel: { queryParam, intervalList, diffCountList },
    } = this.props;
    return (
      <Form onSubmit={this.findDiffData} layout="inline" className={styles.queryForm}>
        <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
          <Form.Item label="选择系统">
            {getFieldDecorator('index', { initialValue: currentSysName })(
              <Select placeholder="所属系统" allowClear={false} onChange={this.sysNameChange}>
                {sysNameList.map(({ index, sysName }) => (<Select.Option key={index} value={index}>{sysName}</Select.Option>))}
              </Select>
            )}
          </Form.Item>
          <Form.Item label="直方图类型">
            {getFieldDecorator('histogramPrefix', { initialValue: queryParam.histogramPrefix })(
              <Select placeholder="直方图类型" allowClear={true}>
                {SqlHistogramArray.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
              </Select>
            )}
          </Form.Item>
        </Row>
        <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
          <Form.Item label="开始时间">
            {getFieldDecorator('startTime', { initialValue: queryParam.startTime })(
              <DatePicker
                style={{ width: undefined }}
                allowClear={false}
                format="YYYY-MM-DD HH:mm:ss"
                disabledDate={current => current > moment().add(0, 'day').endOf('day')}
                showTime={{ defaultValue: moment('08:00:00', 'HH:mm:ss') }}
                showToday={false}
              // renderExtraFooter={() => {
              //   return [
              //     <Tag key='1' color="blue">30天前</Tag>,
              //     <Tag key='2' color="blue">15天前</Tag>,
              //     <Tag key='3' color="blue">7天前</Tag>,
              //     <Tag key='7' color="blue">1天前</Tag>,
              //     <Tag key='4' color="blue">12小时前</Tag>,
              //     <Tag key='5' color="blue">6小时前</Tag>,
              //     <Tag key='6' color="blue">1小时前</Tag>,
              //   ];
              // }}
              />
            )}
          </Form.Item>
          <Form.Item label="时间间隔">
            {getFieldDecorator('interval', { initialValue: queryParam.interval })(
              <Select placeholder="时间间隔" allowClear={true}>
                {intervalList.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
              </Select>
            )}
          </Form.Item>
          <Form.Item label="比较次数">
            {getFieldDecorator('diffCount', { initialValue: queryParam.diffCount })(
              <Select placeholder="比较次数" allowClear={true}>
                {diffCountList.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
              </Select>
            )}
          </Form.Item>
          <Form.Item className={styles.formItemButton}>
            <Button type="primary" htmlType="submit" disabled={queryLoading}>查询</Button>
          </Form.Item>
        </Row>
      </Form>
    );
  }

  getDiffHistogram() {
    const rowStyle = { paddingTop: 24, paddingBottom: 12, borderBottom: '1px solid #ccc' };
    const colStyle = { textAlign: 'center', color: 'blue' };
    const { SqlsDiffModel: { diffData } } = this.props;
    const histogramArray = [];
    for (let i = 0; i < diffData.length;) {
      const index1 = i++;
      const diffData1 = index1 < diffData.length ? diffData[index1] : undefined;
      histogramArray.push((
        <div key={`k-${index1}-div`} style={rowStyle}>
          <Row key={`k-${index1}`} gutter={96}>
            <Col key={`k-${index1}-1`} span={12}>
              {this.getHistogram(diffData1 ? diffData1.data : undefined)}
            </Col>
            <Col key={`k-${index1}-2`} span={12}>
              {this.getPoint(diffData1 ? diffData1.totalData : undefined)}
            </Col>
          </Row>
          <div style={colStyle}>{diffData1 ? diffData1.label : '-'}</div>
        </div>
      ));
    }
    return histogramArray;
  }

  // 直方图
  getHistogram = (histogram) => {
    if (!histogram) return <span />;
    const data = [];
    if (histogram && histogram.titles) {
      lodash.each(histogram.titles, (title, index) => {
        data.push({ x: title, y: histogram.histogramData[index] });
      });
    }
    const scale = {
      x: { type: 'cat', alias: histogram.xaxisTitle },
      y: { type: 'pow', alias: histogram.yaxisTitle },
    };
    // if (this.chart) this.chart.forceFit();
    return (
      <Chart
        forceFit={true}
        // onGetG2Instance={chart => { this.chart = chart }}
        // width={1000}
        height={300}
        padding={['auto', 60, 'auto', 'auto']}
        data={data}
        scale={scale}
      >
        <Axis name="x" title={{ position: "end" }} />
        <Axis name="y" title={{ offset: 70, position: "end" }} />
        <Tooltip crosshairs={{ type: "rect" }} showTitle={false} />
        <Geom type="interval" position="x*y" tooltip="x*y">
          <Label content="y" />
        </Geom>
      </Chart>
    );
  }

  // 气泡图
  getPoint = (totalData) => {
    if (!totalData) return <span />;
    const data = [];
    if (totalData.chartDate && totalData.chartDate.chartList) {
      lodash.each(totalData.chartDate.chartList, item => {
        data.push({
          sql: item.key,
          docCount: item.doc_count,
          sumExecuteCount: item['sum@sql@executeCount'].value,
          sumCostSum: item['sum@sql@cost_sum'].value,
          maxCostMax: item['max@sql@cost_max'].value,
          avgCostSum: numeral(item['avg@sql@cost_sum'].value).format('0.00'),
          maxConcurrentMax: item['max@sql@concurrentMax'].value,
        });
      });
    }
    const scale = {
      'avgCostSum': { type: 'log', alias: '平均时间(ms)' },
      'sumCostSum': { type: 'log', alias: '总时间(ms)' },
      'maxCostMax': { type: 'log', alias: '最大时间(ms)' },
      'sumExecuteCount': { type: 'linear', alias: '执行次数' },
      'maxConcurrentMax': { type: 'linear', alias: '最高并发' },
      'sql': { type: 'cat', alias: 'SQL语句' },
    };
    // if (this.point) this.point.forceFit();
    return (
      <Chart
        forceFit={true}
        // onGetG2Instance={chart => { this.point = chart }}
        // width={1000}
        height={300}
        padding={[60, 'auto', 'auto', 'auto']}
        data={data}
        scale={scale}
      >
        <Tooltip showTitle={false} />
        <Axis name="sumCostSum" title={{ position: "end" }} />
        <Axis name="maxCostMax" title={{ offset: 55, position: "end" }} />
        <Geom
          type="point"
          position="sumCostSum*maxCostMax"
          opacity={0.65}
          shape="circle"
          tooltip="sumCostSum*maxCostMax*avgCostSum*sumExecuteCount*maxConcurrentMax"
          size={["sumExecuteCount", [4, 20]]}
          color={['avgCostSum', ['#008800', '#227700', '#88AA00', '#BBBB00', '#DDAA00', '#EE7700', '#FF5511', '#FF0000']]}
        />
      </Chart>
    );
  }

  render() {
    const { quetyLoading } = this.props;
    return (
      <PageHeaderLayout>
        <Card bordered={false}>
          <div>
            {this.queryForm()}
          </div>
          {/* {this.actionButton()} */}
          <Spin delay={100} size="large" spinning={quetyLoading || false}>
            {this.getDiffHistogram()}
          </Spin>
        </Card>
      </PageHeaderLayout>
    );
  }
}
